package leetcode.code0581;

import java.util.Arrays;

public class Solution extends Solution581 {
	// 先验证排序更慢
	@Override
	public int findUnsortedSubarray(int[] nums) {
		boolean sorted = true;
		for (int i = 1; i < nums.length; i++) {
			if (nums[i] < nums[i - 1]) {
				sorted = false;
				break;
			}
		}
		if (sorted)
			return 0;
		int left = -1; // 左侧第一个逆序的位置
		int right = -1; //
		int[] sort = Arrays.copyOf(nums, nums.length);
		Arrays.sort(sort);
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] != sort[i]) {
				left = i;
				break;
			}
		}
		for (int i = nums.length - 1; i >= 0; i--) {
			if (nums[i] != sort[i]) {
				right = i;
				break;
			}
		}
		return right - left + 1;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		so.debug5();
		so.debug6();
		so.debug8();
		so.debug9();
		so.debug7();
	}

}
